<?php
namespace app\shop\model;

use think\Db;

class ClientRegion extends \ShopModel
{
    protected $table = 'sh_client_region';

    public function ClientRegionDb(){
        return Db::name('client_region');
    }

    //列表
    public function regionList($params){
        $where = [];
        if(!empty($params['query'])){
            $where['region_name'] = ['like','%'.$params['query'].'%'];
        }
        
        $data =  Db::name('client_region')->where($where)->field('region_id,region_name,parent_id')->select();

        return $this->tree($data,0);
    }

    //递归区域
    /**
     * 允许限制级数
     * @param $categories
     * @param int $pid
     * @param int $levelLimit
     * @param int $level
     * @return array
     */
    private function tree($categories, $pid = 0, $levelLimit = 0, $level = 1)
    {
        $children = [];
        foreach ($categories as $category) {
            if ($category['parent_id'] === $pid) {

                if ($levelLimit === 0 || $level < $levelLimit) {
                    $category['children'] = $this->tree($categories, $category['region_id'], $levelLimit, $level + 1);
                }

                $children[] = $category;
            }
        }
        return $children;
    }

    //添加区域
    public function add($params){
        Db::name('client_region')->insert($params);
        return true;
    }

    //区域重命名
    public function rename($params){
        Db::name('client_region')->where('region_id',$params['region_id'])->update(['region_name'=>$params['region_name']]);
        return true;
    }

    //删除区域
    public function del_region($id){
        Db::name('client_region')->where('region_id',$id)->delete();
    }

}